package com.sise.thread.lab01.lab02;


//在多线程的环境里面模拟死锁问题
class ThreadTrain4 implements Runnable{
    private static int trainCount=100;
    public static Object obj=new Object();

    public boolean flag=true;
    //局部变量不会受到线程安全问题的影响
    @Override
    public void run() {
        if(flag){
            while (true) {
                try {
                    Thread.sleep(50);
                    //这里里面使用了里面用的是obj锁
                    synchronized (obj) {
                        sale(); //使用了this锁，sale里面也用了obj锁
                    }
                } catch (Exception e) {
                }
            }
        }else{
            while (true) {
                try {
                    sale(); //使用了obj锁和this锁
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }


    private  synchronized void sale() throws InterruptedException {
        synchronized (obj){
            //同步代码块 使用了this锁和obj锁
            if (trainCount > 0) {
                Thread.sleep(40);
                System.out.println(Thread.currentThread().getName() + ":开始售出第" + (100 - trainCount + 1) + "" + "张票");
            }
            trainCount--;
        }
    }
}


//模拟火车站抢票
public class ThreadMain04 {
    public static void main(String[] args) throws InterruptedException {
        //为了模拟有两个窗口在抢票
        ThreadTrain4 threadTrain4=new ThreadTrain4();
        Thread t1= new Thread(threadTrain4,"窗口1");
        Thread t2= new Thread(threadTrain4,"窗口2");
        t1.start();
        Thread.sleep(40);
        threadTrain4.flag=false;
        t2.start();
    }
}
